let v = new Vue({
    el:'#app',
    data:{
        user:{
            id:"",
            deptId:'',
            deptName:'',
            phone:''
        },
        depts:[],
        isFlag:true
    },
    methods:{
        findUser:function (){
            axios({
                url:`user/findUserLookById/${this.user.id}`
            }).then(response=>{
                this.user = response.data.data;
            })
        },
        checkPhone:function (){
            let regPhone = /^1[3|4|5|8][0-9]\d{6,8}$/;
            this.isFlag = regPhone.test(this.user.phone);
            if (!this.isFlag){
                layer.msg("手机格式不正确，请重新填写");
            }
        },
        findDeptAll:function (){
            axios({
                url:`dept/findAll`
            }).then(response=>{
                this.depts = response.data.data;
            })
        },
        onChangeDeptName:function (){
            this.user.deptName = this.depts[this.user.deptId-1].name;
        },
        doUpdate:function (){
            if (this.isFlag){
                axios({
                    url:`user/doUpdate`,
                    method: "PUT",
                    data: this.user
                }).then(response=>{
                    if (response.data.flag){
                        sessionStorage.setItem("loginUser",JSON.stringify(response.data.data));
                        this.findUser();
                    }
                    layer.msg(response.data.message);
                }).catch(error=>{
                    layer.msg(error.message);
                })
            }else{
                layer.msg("信息填写有误，请检查");
                return false;
            }
        },
        upload:function (e){
            let file = e.target.files[0];
            let param = new FormData(); //创建form对象
            param.append('file',file);//通过append向form对象添加数据
            console.log(param.get('file')); //FormData私有类对象，访问不到，可以通过get判断值是否传进去
            let config = {
                headers:{'Content-Type':'multipart/form-data'}
            }; //添加请求头
            axios.post(`user/upload/${this.user.id}`,param,config)
                .then(response=>{
                    if (response.data.flag){
                        layer.msg("上传成功");
                        //更新session中的用户信息
                        sessionStorage.setItem("loginUser",JSON.stringify(response.data.data));
                        this.findUser();
                    }else{
                        layer.msg("上传失败");
                    }
                })
        }
    },
    created:function (){
        //从session中取出id
        let loginUser = JSON.parse(sessionStorage.getItem("loginUser"));//转换成js对象
        this.user.id = loginUser.id;
        this.findUser();
        this.findDeptAll();
    }
});